package com.lisa.auto.scheduled;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.lisa.auto.entity.C3CarCondStatistics;
import com.lisa.auto.entity.C3RiskFault;
import com.lisa.auto.entity.Vehicle;
import com.lisa.auto.entity.statistics.VehiclesStatisticsPo;
import com.lisa.auto.service.C3CarCondStatisticsService;
import com.lisa.auto.service.C3ReportCarInfoService;
import com.lisa.auto.service.C3RiskFaultService;
import com.lisa.auto.service.IVehicleService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @description: 车况数据汇总
 * @author: huangzhigang
 * @date: 2020-03-28 16:05
 **/
@Component
public class ReportCarScheduled {

    private static final Logger logger = LoggerFactory.getLogger(ReportCarScheduled.class);

    @Autowired
    private IVehicleService vehicleService;
    @Autowired
    private C3ReportCarInfoService reportCarInfoService;
    @Autowired
    private C3RiskFaultService c3RiskFaultService;
    @Autowired
    private C3CarCondStatisticsService c3CarCondStatisticsService;

    @Scheduled(cron="0 0/30 * * * ? ")   //每30分钟执行一次
    public void execute() {
        try {
            // 查询所有车辆数据
            EntityWrapper<Vehicle> wrapper = new EntityWrapper<>();
            List<Vehicle> vehicleList = vehicleService.selectList(wrapper);
            // 非空判断
            if (CollectionUtils.isEmpty(vehicleList)) {
                return;
            }
            vehicleList.stream().forEach(vehicle -> {
                if (vehicle == null) {
                    return;
                }
                Long fleetId = vehicle.getId();
                String fleet = vehicle.getFleet();
                String vin = vehicle.getVin();
                if (StringUtils.isBlank(vin)) {
                    return;
                }
                /*查询车辆总里程*/
                VehiclesStatisticsPo vehiclesStatistics = reportCarInfoService.selVehiclesStatisticsList(vin);
                /*根据车架号查询风险及故障数据*/
                C3RiskFault c3RiskFault = c3RiskFaultService.selectRiskFault(vin);
                Date nowDate = new Date();
                if (c3RiskFault == null && vehiclesStatistics == null) {
                    return;
                }
                C3CarCondStatistics c3CarCondStatistics = null;
                if (c3RiskFault != null && vehiclesStatistics == null) {
                    c3CarCondStatistics = new C3CarCondStatistics(fleetId, fleet, vin, new BigDecimal("0"), c3RiskFault.getStartTime(),
                            c3RiskFault.getEndTime(), dataTypDb(c3RiskFault.getType()), nowDate);
                }
                if (c3RiskFault == null && vehiclesStatistics != null) {
                    c3CarCondStatistics = new C3CarCondStatistics(fleetId, fleet, vin, new BigDecimal(vehiclesStatistics.getTotalDistance()), nowDate,
                            nowDate, "1", nowDate);
                }
                if (c3RiskFault != null && vehiclesStatistics != null) {
                    c3CarCondStatistics = new C3CarCondStatistics(fleetId, fleet, vin, new BigDecimal(vehiclesStatistics.getTotalDistance()), c3RiskFault.getStartTime(),
                            c3RiskFault.getEndTime(), dataTypDb(c3RiskFault.getType()), nowDate);
                }
                if (c3CarCondStatistics != null ) {
                    if (c3CarCondStatistics.getTotalDistance().compareTo(new BigDecimal("0.00"))!=1){
                        EntityWrapper<C3CarCondStatistics> ew = new EntityWrapper<>();
                        ew.where(" to_days(gmt_create) = to_days(now()) ").eq("vin", vin).eq("fleet", fleet);
                        List<C3CarCondStatistics> isExist = c3CarCondStatisticsService.selectList(ew);
                        if (CollectionUtils.isNotEmpty(isExist)){
                            C3CarCondStatistics c3CarCondStatistics1 = isExist.get(0);
                            if (c3CarCondStatistics.getTotalDistance()!=null && c3CarCondStatistics1.getTotalDistance()!=null ){
                                BigDecimal distance = c3CarCondStatistics.getTotalDistance().subtract(c3CarCondStatistics1.getTotalDistance());
                                c3CarCondStatistics.setDistance(distance.add(c3CarCondStatistics1.getDistance()==null?new BigDecimal("0.00"):c3CarCondStatistics1.getDistance()));
                            }
                            EntityWrapper<C3CarCondStatistics> entityWrapper = new EntityWrapper<>();
                            entityWrapper.eq("id", isExist.get(0).getId());
                            c3CarCondStatisticsService.update(c3CarCondStatistics, entityWrapper);
                            return;
                        }
                        c3CarCondStatisticsService.insert(c3CarCondStatistics);
                    }
                }
            });
        } catch (Exception e) {
            logger.info(e.getMessage(), e);
        }
    }


    /**
     * 车况数据类型处理
     * @param type 数据类型
     * @return
     */
    static String dataTypDb(String type){
        switch(type){
            case "30" :
                return "2";
            case "20" :
                return "3";
            default : return "1";
        }
    }

}
